package net.yihang.miaosha.service;

import net.yihang.miaosha.controller.result.CodeMsg;
import net.yihang.miaosha.dao.MiaoshaUserDao;
import net.yihang.miaosha.domain.MiaoshaUser;
import net.yihang.miaosha.domain.MiaoshaUserKey;
import net.yihang.miaosha.util.Md5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginService {

    @Autowired
    private MiaoshaUserDao miaoshaUserDao;


    public CodeMsg login(long mobile, String formPassword, AfterLoginSuccess afterLoginSuccess) {
        if (StringUtils.isEmpty("" + mobile)) {
            return CodeMsg.MOBILE_EMPTY;
        }
        if (StringUtils.isEmpty(formPassword)) {
            return CodeMsg.PASSWORD_EMPTY;
        }
        MiaoshaUser user = miaoshaUserDao.findById(mobile);
        if (user == null) {
            return CodeMsg.MOBILE_NOTEXIST;
        }
        if (!Md5Util.verifyDbPass(formPassword, user.getSalt(), user.getPassword())) {
            return CodeMsg.PASSWORD_ERROR;
        }
        MiaoshaUserKey key = MiaoshaUserKey.newToken();
        if (afterLoginSuccess != null) {
            afterLoginSuccess.execute(key, user);
        }
        return CodeMsg.LOGIN_SUCCESS;
    }

}
